package com.xxwy.ddu.security.app.impl;

import com.xxwy.ddu.security.code.vaildatecode.ValidateCode;
import com.xxwy.ddu.security.code.vaildatecode.ValidateCodeRepository;
import com.xxwy.ddu.security.code.vaildatecode.ValidateCodeType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author xxwy
 * on 2018/8/29 0029
 * 基于redis的验证码存取器，避免由于没有session导致无法存取验证码的问题
 */
@Component
public class AppValidateCodeRepository implements ValidateCodeRepository {


    @Autowired
    private RedisTemplate<String,Serializable> xxredisTemplate;


    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
        xxredisTemplate.opsForValue().set(buildkey(request,type),code,30,TimeUnit.MINUTES);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
        Object value = xxredisTemplate.opsForValue().get(buildkey(request, type));
        if (value == null) {
            return null;
        }
        return (ValidateCode)value;
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType type) {
        xxredisTemplate.delete(buildkey(request,type));
    }

    private String buildkey(ServletWebRequest request, ValidateCodeType type) {
        String deviceid = request.getHeader("deviceId");
        if (StringUtils.isBlank(deviceid)){
            throw new RuntimeException("请在请求头中添加deviceId");
        }
        return "code:"+type.toString().toLowerCase()+":"+deviceid;
    }
}
